#!/usr/bin/env python3
"""
工业物联网数据采集系统 - 主程序入口
"""

import sys
import os
import logging
import signal
import threading
import time
from pathlib import Path

# 添加项目根目录到Python路径
sys.path.insert(0, str(Path(__file__).parent))

from core.engine import DataEngine
from services.storage import StorageService
from services.alarm import AlarmService
from services.scheduler import SchedulerService
from web.app import create_app
from config.config import load_config

class IoTCollectorMain:
    def __init__(self):
        self.config = None
        self.engine = None
        self.storage_service = None
        self.alarm_service = None
        self.scheduler_service = None
        self.web_app = None
        self.running = False
        
    def setup_logging(self):
        """配置日志系统"""
        log_level = self.config.get('logging', {}).get('level', 'INFO')
        log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        
        logging.basicConfig(
            level=getattr(logging, log_level),
            format=log_format,
            handlers=[
                logging.StreamHandler(sys.stdout),
                logging.FileHandler('logs/iot_collector.log', encoding='utf-8')
            ]
        )
        
    def load_configuration(self):
        """加载配置文件"""
        try:
            self.config = load_config()
            logging.info("配置加载成功")
        except Exception as e:
            logging.error(f"配置加载失败: {e}")
            sys.exit(1)
            
    def initialize_services(self):
        """初始化各个服务组件"""
        try:
            # 存储服务
            self.storage_service = StorageService(self.config.get('storage', {}))
            logging.info("存储服务初始化完成")
            
            # 报警服务
            self.alarm_service = AlarmService(self.config.get('alarm', {}))
            logging.info("报警服务初始化完成")
            
            # 任务调度服务
            self.scheduler_service = SchedulerService()
            logging.info("调度服务初始化完成")
            
            # 数据采集引擎
            self.engine = DataEngine(
                storage_service=self.storage_service,
                alarm_service=self.alarm_service,
                max_workers=self.config.get('engine', {}).get('max_workers', 10)
            )
            logging.info("数据采集引擎初始化完成")
            
            # Web应用
            self.web_app = create_app(
                engine=self.engine,
                storage=self.storage_service,
                alarm=self.alarm_service,
                scheduler=self.scheduler_service,
                config=self.config.get('web', {})
            )
            logging.info("Web应用初始化完成")
            
        except Exception as e:
            logging.error(f"服务初始化失败: {e}")
            sys.exit(1)
            
    def load_device_config(self):
        """加载设备配置"""
        try:
            from services.config_manager import ConfigManager
            
            config_manager = ConfigManager()
            devices_config = config_manager.load_devices()
            
            logging.info(f"发现 {len(devices_config)} 个设备配置")
            
            for device_config in devices_config:
                try:
                    device_name = device_config.get('name')
                    driver_type = device_config.get('type')
                    
                    if not device_name or not driver_type:
                        logging.warning(f"设备配置缺少名称或类型: {device_config}")
                        continue
                    
                    if not device_config.get('enabled', True):
                        logging.info(f"设备 {device_name} 被禁用，跳过加载")
                        continue
                    
                    # 创建设备驱动实例
                    driver = self._create_device_driver(driver_type, device_config)
                    if driver:
                        self.engine.add_device(device_name, driver)
                        logging.info(f"设备 {device_name} ({driver_type}) 加载成功")
                    else:
                        logging.error(f"设备 {device_name} 驱动创建失败")
                    
                except Exception as e:
                    logging.error(f"设备 {device_config.get('name', 'Unknown')} 加载失败: {e}")
                    
        except Exception as e:
            logging.error(f"加载设备配置失败: {e}")
    
    def _create_device_driver(self, driver_type: str, device_config: dict):
        """创建设备驱动实例"""
        try:
            if driver_type == 'modbus':
                from core.drivers.modbus import ModbusDriver
                return ModbusDriver(device_config)
            elif driver_type == 's7':
                from core.drivers.s7 import S7Driver
                return S7Driver(device_config)
            elif driver_type == 'opcua':
                from core.drivers.opcua import OpcuaDriver
                return OpcuaDriver(device_config)
            elif driver_type == 'mqtt':
                from core.drivers.mqtt import MqttDriver
                return MqttDriver(device_config)
            else:
                logging.error(f"不支持的设备类型: {driver_type}")
                return None
                
        except ImportError as e:
            logging.error(f"导入驱动模块失败: {e}")
            return None
        except Exception as e:
            logging.error(f"创建驱动实例失败: {e}")
            return None
            
    def start(self):
        """启动系统"""
        logging.info("正在启动工业物联网数据采集系统...")
        
        # 创建必要的目录
        os.makedirs('logs', exist_ok=True)
        os.makedirs('data', exist_ok=True)
        
        # 加载配置
        self.load_configuration()
        
        # 设置日志
        self.setup_logging()
        
        # 初始化服务
        self.initialize_services()
        
        # 加载设备配置
        self.load_device_config()
        
        # 启动数据采集引擎
        self.engine.start()
        
        # 启动调度服务
        self.scheduler_service.start()
        
        # 启动Web服务
        web_config = self.config.get('web', {})
        web_thread = threading.Thread(
            target=self.web_app.run,
            kwargs={
                'host': web_config.get('host', '0.0.0.0'),
                'port': web_config.get('port', 5000),
                'debug': web_config.get('debug', False),
                'use_reloader': False,  # 禁用重新加载器以避免信号处理问题
                'threaded': True
            }
        )
        web_thread.daemon = True
        web_thread.start()
        
        self.running = True
        logging.info("系统启动完成")
        
        # 设置信号处理
        signal.signal(signal.SIGINT, self.signal_handler)
        signal.signal(signal.SIGTERM, self.signal_handler)
        
        # 主循环
        try:
            while self.running:
                time.sleep(1)
        except KeyboardInterrupt:
            self.stop()
            
    def stop(self):
        """停止系统"""
        logging.info("正在停止系统...")
        self.running = False
        
        if self.engine:
            self.engine.stop()
            
        if self.scheduler_service:
            self.scheduler_service.stop()
            
        logging.info("系统已停止")
        
    def signal_handler(self, signum, frame):
        """信号处理函数"""
        logging.info(f"收到信号 {signum}，准备停止系统")
        self.stop()

def main():
    """主函数"""
    collector = IoTCollectorMain()
    collector.start()

if __name__ == "__main__":
    # 设置调试模式
    logging.basicConfig(
        level=logging.DEBUG,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )
    
    logger = logging.getLogger(__name__)
    logger.info("🚀 启动工业物联网数据采集系统（调试模式）")
    
    try:
        main()
    except KeyboardInterrupt:
        logger.info("👋 系统正常退出")
    except Exception as e:
        logger.error(f"💥 系统异常退出: {e}")
        import traceback
        traceback.print_exc() 